import 'dart:io';

import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:path/path.dart';
import 'package:test2/base/base_page.dart';
import 'package:test2/model/game.dart';
import 'package:test2/style/style.dart';
import 'package:test2/util/PicUtil.dart';
import 'package:test2/util/bus.dart';
import 'package:test2/util/widget.dart';
import 'package:test2/widget/image.dart';

class GameAdd extends StatefulWidget {
  const GameAdd({super.key, this.game});

  final Game? game;

  @override
  State<GameAdd> createState() => _GameAddState();
}

class _GameAddState extends BaseState<GameAdd> {
  bool edit = false;
  late Game game;
  File? pic;
  bool picChanged = false;
  TextEditingController _textEditingController = TextEditingController();

  @override
  void initState() {
    if (widget.game == null) {
      game = Game(name: "", pic: "", top: false);
      edit = true;
    } else {
      game = Game(
        name: widget.game!.name,
        pic: widget.game!.pic,
        top: widget.game!.top,
      );
    }
    _textEditingController.text = game.name;
    if (widget.game?.key != null) {
      pic = File(PicUtil.picRootPath + game.pic);
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.game?.key == null ? "添加游戏" : "修改游戏"),
        actions: [
          if (!edit)
            IconButton(
              onPressed: () {
                setState(() {
                  edit = true;
                });
              },
              icon: Icon(Icons.edit),
            ),
        ],
      ),
      floatingActionButton: edit
          ? FloatingActionButton(
              onPressed: () {
                commit();
              },
              child: Icon(Icons.check),
            )
          : null,
      body: SizedBox.expand(
        child: SingleChildScrollView(
          padding: EdgeInsets.all(16),
          child: Column(
            spacing: 20,
            children: [
              TextField(
                readOnly: !edit,
                controller: _textEditingController,
                decoration: InputDecoration(labelText: "游戏名"),
                onChanged: (s) {
                  game.name = s;
                },
              ),

              ImagePickView(
                showScreenshot: false,
                enable: edit,
                imageProvider: pic == null ? null : FileImage(pic!),
                title: "封面",
                onPick: (file) {
                  setState(() {
                    pic = file;
                    picChanged = true;
                  });
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  void commit() async {
    if (game.name.isEmpty) {
      showToast("请输入游戏名");
      return;
    }
    if (pic == null) {
      showToast("请选择图片");
      return;
    }

    // 修改图片要删除旧的

    if (picChanged) {
      // 删除旧图片
      if (widget.game?.key != null) {
        game.deletePic();
      }

      print("save");
      String picName = PicUtil.savePic(pic!.readAsBytesSync());
      if (picName.isEmpty) {
        showToast("图片保存出错");
        return;
      }

      game.pic = picName;
    }

    if (widget.game?.key == null) {
      Hive.box<Game>("game").add(game);
    } else {
      Hive.box<Game>("game").put(widget.game?.key, game);
    }

    bus.emit(EventType.game);

    finish();
  }
}
